<template>
  <div class="component-addr">
    <div class="component-mainHeader">
      <div class="top">
        <div class="topleft">
          <p>
            <span class="iconfont" style="color:#1abc9a;margin-right:3px;">&#xe607;</span>地址管理
          </p>
        </div>
        <div class="topright">
          <el-button type="info" @click="$router.go(0)">
            <span style="font-weight:700;margin-right:5px;" class="iconfont">&#xe662;</span>刷新
          </el-button>
        </div>
      </div>
    </div>
    <div class="body_container">
      <div class="body_left">
        <button @click="addChange" :class="isAdd?'cancel':''">{{isAdd?'取消添加':'添加子节点'}}</button>
        <button @click="del">删除选中节点</button>
        <el-input
          placeholder="输入关键字进行筛选"
          v-model="filterText"
          style="width:216px;margin:10px auto;"
        ></el-input>
        <el-tree
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          :highlight-current="true"
          :check-on-click-node="true"
          ref="tree2"
          @node-click="setCurrent"
        ></el-tree>
      </div>
      <div class="body_right">
        <div class="right_header">
          <p>{{isAdd?'添加子节点':'地址设置'}}</p>
          <button @click="add">{{isAdd?'确认添加':'保存设置'}}</button>
        </div>
        <div class="right_body">
          <el-form
            ref="form"
            :model="form"
            label-width="80px"
            :inline="true"
            style="text-align:left;"
          >
            <el-form-item label="父级节点：" label-width="100px">
              <el-input v-model="form.parent" :disabled="true" style="width:240px;"></el-input>
            </el-form-item>
            <!-- <el-form-item label="父级代码：" label-width="100px">
              <el-input v-model="form.perentId" :disabled="true" style="width:240px;"></el-input>
            </el-form-item>-->
            <el-form-item label="子级名称：" label-width="100px">
              <el-input v-model="form.label" placeholder="请输入名称" style="width:240px;" clearable></el-input>
            </el-form-item>
            <!-- <el-form-item label="子级代码：" label-width="100px">
              <el-input v-model="form.level" placeholder="请输入代码" style="width:240px;" clearable></el-input>
            </el-form-item>-->
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "addrManage",
  data() {
    return {
      // 搜索框的值
      filterText: "",
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 添加/编辑
      isAdd: false,
      // 当前选中项的节点和数据
      currentNode: {},
      currentData: {},
      // 树状图的数据
      data: [],
      // 表单的数据
      form: {
        parent: "", //父节点名称
        perentId: "", //父级id  parentCode
        label: "", //子级名称 label
        level: "", //子级id
        children: []
      }
    };
  },
  mounted() {
    this.dataInit();
  },
  methods: {
    //权限列表
    dataInit() {
      let that = this;
      let suCb = function(res) {
        console.log(res.data.data.options);
        that.data = res.data.data.options;
      };
      let erCb = function(res) {
        console.log(res);
      };
      let postData = {};
      let palyParam = {
        url: "/api/web/SysAddressManagement/selectTreeAddress",
        methods: "post",
        data: postData,
        success: suCb,
        error: erCb
      };
      that.$https(palyParam);
    },
    // 点击添加子部门按钮 切换isAdd的状态 把当前选中项的data和node传入setCurrent重置
    addChange() {
      this.isAdd = !this.isAdd;
      if (this.isAdd == false && JSON.stringify(this.currentData) == "{}") {
        console.log(1);
        return false;
      } else {
        console.log(this.currentData);
        this.setCurrent(this.currentData, this.currentNode);
      }
    },
    //  获取当前选中项的data和node 并赋值给form中的子项，然后将form.children重置为空数组
    setCurrent(data, node) {
      console.log(data);
      console.log(node);
      this.currentData = data;
      this.currentNode = node;
      // 如果是添加 则父节点为当前选中的节点 其他为空 让用户输入
      if (this.isAdd) {
        this.form.parent = data.label;
        this.form.label = "";
        this.form.level = data.level;
        this.form.perentId = data.value;
        this.form.children = [];
      } else {
        // 如果是编辑 则父节点为当前节点的parent.data.label 其他信息自动填充 然后children为空数组
        this.form.parent =
          node.parent.data.label == undefined
            ? "无父节点"
            : node.parent.data.label;
        this.form.label = data.label;
        this.form.level = data.level;
        this.form.perentId = data.value;
        this.form.children = [];
      }
      console.log(this.form);
    },
    // 搜索框 过滤函数
    filterNode(level, data) {
      if (!level) return true;
      return data.label.indexOf(level) !== -1;
    },
    add() {
      // 先判断form.label不能为空
      if (this.form.label == "" || (!this.form.parent && !this.isAdd)) {
        this.$erMsg('请先填写子级名称或切换到添加状态！')
      } else {
        // 如果是添加 就利用JSON序列化反序列化深拷贝form并赋值给newChild 然后push进当前数据中的children数组
        if (this.isAdd) {
          if(this.form.parentId=="" || this.form.parentId==undefined){
            this.form.parentId='0';
            this.addChildNode(this.form)
          }else{
            let newChild = JSON.parse(JSON.stringify(this.form));
            console.log(this.currentData);
            this.currentData.children.push(newChild);
            this.addChildNode(this.form);
          }
          //          console.log(this.form)
        } else {
          // 如果是编辑 则将改变的数据赋值给当前选中项的data 然后清空form 初始化父节点的显示框
          this.currentData.label = this.form.label;
          this.currentData.code = this.form.parentId;
          this.addChildNode(this.form, 1);
        }
        this.form = {
          parent: "",
          label: "",
          level: "",
          perentId: "",
          children: []
        };
        // this.form.parent = this.currentNode.data.label;
        // this.form.perentId = this.currentNode.data.code;
      }
    },
    del() {
      // 找到父节点 没有父节点则为当前节点 然后找寻对应下标 用splice从当前数组中删除
      console.log(this.currentNode);
      if(this.form.parent){
        const parent = this.currentNode.parent;
      console.log(parent);
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.label === this.currentData.label);
      children.splice(index, 1);
      console.log(this.form);
      this.deletChildNode(this.form);
      this.form = {
        parent: "",
        label: "",
        level: "",
        perentId: "",
        children: []
      };
      this.isAdd = false;
      }else{
        this.$erMsg('请先选择要删除的节点')
      }
    },
    //    添加子节点函数
    addChildNode(val, edit) {
      let that = this;
      let suCb = function(res) {
        if (edit === 1) {
          that.$message({
            message: "编辑成功",
            type: "success"
          });
        } else {
          that.$message({
            message: "添加成功",
            type: "success"
          });
        }
        that.isAdd = false;
        that.currentNode = {};
        that.currentData = {};
        that.dataInit();
      };
      let erCb = function(res) {
        that.$alert(res.data.message, "提示", {
          confirmButtonText: "确定",
          callback: action => {
            that.isAdd = false;
          }
        });
      };
      let postData = {
        level: val.level,
        name: val.label,
        parentId: val.perentId
      };
      let palyParam = {
        url: "/api/web/SysAddressManagement/addAddress",
        methods: "post",
        data: postData,
        success: suCb,
        error: erCb
      };
      if (edit === 1) {
        (palyParam.url = "/api/web/SysAddressManagement/updateAddress"),
          (palyParam.data = {
            name: val.label,
            id: val.perentId
          });
      }
      console.log(postData);
      that.$https(palyParam);
    },
    //删除子节点
    deletChildNode(val) {
      let that = this;
      let suCb = function(res) {
        that.$message({
          message: "删除成功",
          type: "success"
        });
        that.dataInit();
        that.currentNode = {};
        that.currentData = {};
      };
      let erCb = function(res) {
        console.log(res);
      };
      let postData = {
        id: val.perentId
      };
      let palyParam = {
        url: "/api/web/SysAddressManagement/deleteAddressById",
        methods: "post",
        data: postData,
        success: suCb,
        error: erCb
      };
      console.log(val)
      that.$https(palyParam);
    }
  },
  watch: {
    // 侦听 当前搜索框的值
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  }
};
</script>

<style scoped>
.body_container {
  width: 1100px;
  margin: 30px auto;
  display: flex;
  justify-content: space-between;
}

.body_left {
  width: 640px;
  border: 1px solid rgba(228, 228, 228, 1);
  background-color: rgba(255, 255, 255, 1);
  min-height: 800px;
  padding: 10px;
  box-sizing: border-box;
}

.body_right {
  width: 440px;
  min-height: 800px;
  border: 1px solid rgba(228, 228, 228, 1);
}

.body_right .right_header {
  border-bottom: 1px solid rgba(228, 228, 228, 1);
  height: 45px;
  line-height: 45px;
  display: flex;
  justify-content: space-between;
  background-color: #f3f3f3;
}

.body_right .right_header p {
  font-size: 14px;
  margin-left: 15px;
  color: #666;
}

.body_right .right_body {
  padding: 20px 10px;
}

.body_container button {
  height: 35px;
  line-height: 35px;
  border: 1px solid #eee;
  border-radius: 2px;
  background-color: #fff;
  font-size: 14px;
  color: #666;
  width: 100px;
  margin: 5px;
}

.body_container button:hover,
.body_container button.cancel {
  color: #fff;
  background-color: #1abc9c;
}
</style>

